package com.etoak.service.impl;

import cn.hutool.json.JSONUtil;
import com.etoak.common.core.constant.CommonConstant;
import com.etoak.common.web.context.LoginContext;
import com.etoak.entity.CartDTO;
import com.etoak.redis.RedisService;
import com.etoak.service.CartService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CartServiceImpl implements CartService {
    @Autowired
    RedisService redisService;
    @Override
    public void add(CartDTO dto) {
        redisService.hset(this.getCartKey(),dto.getDishesId().toString(), JSONUtil.toJsonStr(dto));

    }

    @Override
    public List<CartDTO> getList() {
        return redisService
                .hvals(getCartKey())
                .stream()
                .map(m -> JSONUtil.toBean(m,CartDTO.class))
                .toList();
    }

    @Override
    public void deleteDishes(int id) {
        redisService.hdel(getCartKey(),String.valueOf(id));
    }

    @Override
    public void clearCart() {
        redisService.del(getCartKey());
    }

    private String getCartKey(){
        return CommonConstant.REDIS_CART_PREFIX + LoginContext.getUserId();
    }
}
